package com.example.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.Objects;
import java.util.UUID;

@Controller
public class FileController {

    private static final String DIR_PATH = "D:\\145\\FileDownloadAndUpload";

    @GetMapping("/upload")
    public String upload(){
        return "upload";
    }

    @PostMapping("/upload")
    public String uploadFile(MultipartFile[] files, Model model){
        File directory = new File(DIR_PATH);
        if(!directory.exists() && !directory.mkdirs()){
            model.addAttribute("msg","创建目录失败，请检查服务器配置");
            return "upload";
        }

        StringBuilder messages = new StringBuilder();
        for(MultipartFile file : files){
            if(file.isEmpty()){
                messages.append("请选择文件进行上传。 <br>");
                continue;
            }
            String fileName  =file.getOriginalFilename();
            String uniqueFileName = UUID.randomUUID() + "_" + Objects.requireNonNull(fileName);
            File destFile = new File(DIR_PATH,uniqueFileName);
            try{
                file.transferTo(destFile);
                messages.append("文件").append(fileName).append("上传成功。<br>");
            } catch (IOException e) {
               messages.append("文件").append(fileName).append("上传失败").append(e.getMessage()).append("br");
            }
        }
        model.addAttribute("msg",messages.toString());
        return "upload";
    }


    @GetMapping("/download")
    public String download(Model model) {
        File dir = new File(DIR_PATH);
// 检查目录是否存在且不为空
        if (dir.exists() && dir.list().length > 0) {
// 获取目录下的所有文件名
            String[] files = dir.list();
// 将文件名数组添加到model中，以便在视图中显示
            model.addAttribute("files", files);
        } else {
// 如果目录不存在或为空，向model添加提示信息
            model.addAttribute("msg", "无下载文件");
        }
        return "download";
    }
// 处理具体文件的下载请求
    @GetMapping("/downloadfile")
    public ResponseEntity<byte[]> downloadFile(@RequestParam("filename") String
                                                       fileName) {
// 构造文件的完整路径
        File file = new File(DIR_PATH, fileName);
        try {
// 设置HTTP响应头
            HttpHeaders headers = new HttpHeaders();
// 设置为附件形式下载，避免浏览器直接打开
            headers.setContentDispositionFormData("attachment",
                    URLEncoder.encode(fileName, "UTF-8"));
// 指定内容类型为二进制流，适用于任何类型的文件
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
// 读取文件为字节数组，并构造响应实体
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(Files.readAllBytes(file.toPath()));
        } catch (IOException e) {
// 文件读取异常处理
            e.printStackTrace();
// 如果读取文件发生异常，返回异常信息并设置HTTP状态码为EXPECTATION_FAILED
            return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED)
                    .body(e.getMessage().getBytes());
        }
    }

}
